﻿using Microsoft.Extensions.Logging;
using JESAI.Application.Abstractions.Sys;
using JESAI.Biz.Data.Commons.Consts;
using JESAI.Caching;
using JESAI.Core.Attributes;
using JESAI.Core.Encryptor;
using JESAI.Core.Util.Date;
using JESAI.DDD.Services;
using JESAI.DDD.Services.Abstract;
using JESAI.Platform.Domain.Admin.Entities;
using JESAI.Platform.Domain.Admin.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.Application.Service.Sys
{
    [AppService]
    public class WebApiAuthorizationService : ApplicationService, IWebApiAuthorizationService
    {
        private readonly IAppRepository _appRepository;
        private readonly ILogger<WebApiAuthorizationService> _logger;
        private readonly CacheManager _cacheManager;
        public WebApiAuthorizationService(IAppRepository appRepository,
            ILogger<WebApiAuthorizationService> logger, 
            CacheManager cacheManager)
        {
            _appRepository = appRepository;
            _logger=logger;
            _cacheManager = cacheManager;
        }

        public async void LoadAllAppInfoToCacheAsync()
        {
           List<AppModel> appModels=await _appRepository.GetListAsync();
           foreach(var appModel in appModels)
           {
                _cacheManager.Del(CacheConst.AppCacheKeyPrefix + appModel.AppId);
                _cacheManager.Set(CacheConst.AppCacheKeyPrefix + appModel.AppId, appModel);
           }
        }

        /// <summary>
        /// 检验认证授权
        /// </summary>
        /// <param name="appKey"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool WebApiAuthorize(string appKey, string token)
        {
            var appInfo = _cacheManager.GetOrAdd<AppModel>(CacheConst.AppCacheKeyPrefix + appKey, (val) =>
            {
                return _appRepository.GetFirst(p => p.AppId == appKey);
            });
               
            var flag = false;
            if (appInfo != null)
            {
                var serect = appInfo.Secret;
                try
                {
                    var timeStamp = AesEncryptor.Instance.Decrypt(token, serect);
                    if (!string.IsNullOrWhiteSpace(timeStamp))
                    {
                        if (long.TryParse(timeStamp, out long timeStampL))
                        {
                            long currentTimeStamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
                            if (currentTimeStamp - timeStampL < (long)1000*5 * 60)
                            {
                                flag = true;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "解密失败！");
                }
            }
            return flag;
        }       
    }
}
